<template>
  <div class="application-body" :style="bodyStyle">
    <div class="application-header" :class="customClass">
      <header-view :layout="layout" @callBack="headerCallBack" />
    </div>
    <div class="application-content" :class="customClass">
      <div style="width: 100%;height: 100%;position:relative">
        <content-view
          v-if="isMore === false && isEntity === false"
          ref="content"
          :menu-id="menuId"
          :layout="layout"
          @parent-more="moreCallBack"
          @parent-entity="parentEntity"
        />
        <more-view
          v-if="isMore === true && isEntity === false"
          ref="more"
          :column="column"
          :layout="layout"
          @callBack="menuCallBack"
          @parent-entity="parentEntity"
        />
        <entity-view
          v-if="isMore === false && isEntity === true"
          ref="entity"
          :column="entityTemp"
          :layout="layout"
          @callBack="entityCallBack"
          @callBackColumn="moreCallBack"
          @callBackMenu="menuCallBack"
        />
      </div>
    </div>
    <div class="application-footer" :class="customClass">
      <div style="width: 100%;height: 100%;position:relative">
        <footer-view :layout="layout" />
      </div>
    </div>
    <div class="application-tool" :class="customClass">
      <tools-view :layout="layout" :flex="customClass" />
    </div>
    <div v-if="systemList" class="custom-iframe">
      <iframe
        v-for="(item, index) in systemList"
        :key="'iframe-' + index"
        :src="item.url + item.indexUrl"
      />
    </div>
  </div>
</template>
<script>
import ContentView from './components/content';
import MoreView from './components/more';
import FooterView from './components/footer';
import HeaderView from './components/header';
import ToolsView from './components/tools';
import EntityView from './components/entity';
import { getToken } from '@/utils/auth';
import { guestLayout, userLayout } from '@/api/portal/user/layout';
import { Client } from '@stomp/stompjs';
import SockJS from 'sockjs-client';
import { saveSystemVital } from '@/api/config/config';
import { queryAllSystem } from '@/api/system/usystem';
export default {
  name: 'PortalNewIndex',
  components: {
    ContentView,
    FooterView,
    HeaderView,
    ToolsView,
    MoreView,
    EntityView
  },
  data() {
    return {
      customClass: 'right',
      height: 0,
      bodyHeight: null,
      layout: {},
      menuId: null,
      isMore: false,
      isEntity: false,
      column: {},
      entityTemp: {},
      bodyStyle: {},
      systemList: [],
      timer: null,
      refreshTime: 900 // 单位秒
    };
  },
  watch: {
    token(val, oldVal) {
      // 如果一开始没有，现在有了，说明刚登录，连接websocket
      if (!oldVal && val) {
        // this.initWebsocket()
      }
      // 如果原先由，现在没有了，说明退出登录，断开websocket
      if (oldVal && !val) {
        // this.closeWebsocket()
      }
    },
    layout(val, oldVal) {
      if (val.qybjt === true) {
        if (val.bakRepeat === true) {
          this.bodyStyle = {
            background: 'url(' + val.bjt + ') no-repeat',
            backgroundSize: '100% 100%'
          };
        } else {
          this.bodyStyle = { background: 'url(' + val.bjt + ') repeat' };
        }
      } else {
        // 未启用背景图
        this.bodyStyle = { backgroundColor: val.backColor };
      }
    }
  },
  created() {
    if (this.customClass !== 'top') {
      this.bodyHeight = { minHeight: document.body.offsetHeight - 68 + 'px' };
    } else {
      this.bodyHeight = { minHeight: document.body.offsetHeight - 108 + 'px' };
    }
    this.initLayout();
    // 只有登录后才连接
    if (this.token) {
      //  this.initWebsocket()
    }
    this.saveVital();
    this.initAllSystem();
  },
  destroyed() {
    //  this.closeWebsocket()
    clearInterval(this.timer);
  },
  mounted() {
    const tak = this;
    this.$nextTick(() => {
      window.addEventListener('resize', () => {
        // 监听浏览器窗口大小改变
        // 浏览器变化执行动作
        if (tak.customClass !== 'top') {
          tak.bodyHeight = {
            minHeight: document.body.offsetHeight - 68 + 'px'
          };
        } else {
          tak.bodyHeight = {
            minHeight: document.body.offsetHeight - 108 + 'px'
          };
        }
      });
    });
  },
  methods: {
    initLayout() {
      if (getToken()) {
        userLayout().then(res => {
          const { data } = res;
          this.layout = data;
        });
      } else {
        guestLayout().then(res => {
          const { data } = res;
          this.layout = data;
        });
      }
    },
    async saveVital() {
      saveSystemVital()
        .then(res => {})
        .catch(() => {
          console.log('记录信息失败！');
        });
    },
    headerCallBack(id) {
      this.isMore = false;
      this.isEntity = false;
      this.menuId = id;
      this.$nextTick(() => {
        this.$refs.content.init(this.menuId, this.layout);
      });
    },
    moreCallBack(data) {
      if (undefined !== data && data !== null) {
        this.isMore = true;
        this.isEntity = false;
        this.column = data;
        this.$nextTick(() => {
          this.$refs.more.init(this.column, this.layout);
        });
      }
    },
    parentEntity(data) {
      if (undefined !== data && data !== null) {
        this.entityTemp = data;
        this.isMore = false;
        this.isEntity = true;
        this.$nextTick(() => {
          this.$refs.entity.init(data, this.layout);
        });
      }
    },
    menuCallBack(data) {
      if (undefined !== data && data !== null) {
        this.isMore = false;
        this.isEntity = false;
        this.menuId = data;
        this.$nextTick(() => {
          this.$refs.content.init(this.menuId, this.layout);
        });
      }
    },
    entityCallBack(data) {},
    initAllSystem() {
      queryAllSystem()
        .then(res => {
          const { content } = res;
          this.systemList = content;
          this.timer = setTimeout(this.initAllSystem, this.refreshTime * 1000);
        })
        .catch(() => {
          console.log('获取失败！');
        });
    },
    initWebsocket() {
      this.stompClient = new Client({
        brokerURL: '', // 可以不赋值，因为后面用SockJS来代替
        connectHeaders: { APEXEDU: this.token },
        debug: function(str) {
          console.log(str);
        },
        reconnectDelay: 10000, // 重连时间
        heartbeatIncoming: 4000,
        heartbeatOutgoing: 4000
      });
      // 用SockJS代替brokenURL
      this.stompClient.webSocketFactory = function() {
        return new SockJS('/socket');
      };
      // 连接
      this.stompClient.onConnect = frame => {
        this.stompClient.subscribe('/send/message/notice/all', res => {
          const body = JSON.parse(res.body);
          this.$notify.info({
            title: body.title,
            dangerouslyUseHTMLString: true,
            message: body.content
          });
        });
        this.stompClient.subscribe('/user/send/message/notice/entity', res => {
          const body = JSON.parse(res.body);
          this.$notify.warning({
            title: body.title,
            dangerouslyUseHTMLString: true,
            message: body.content
          });
        });
        // 新版不用send而是publish
        this.stompClient.publish({
          destination: '/send/hello',
          body: '123'
        });
      };
      // 错误
      this.stompClient.onStompError = function(frame) {
        console.log('Broker reported error: ' + frame.headers['message']);
        console.log('Additional details: ' + frame.body);
        // 这里不需要重连了，新版自带重连
      };
      // 启动
      this.stompClient.activate();
    },
    closeWebsocket() {
      if (this.stompClient !== undefined && this.stompClient !== null) {
        this.stompClient.disconnect(() => {
          console.log('关闭链接');
        });
      }
    }
  }
};
</script>

<style scoped>
.application-body {
  width: 100%;
  height: 100%;
  background-color: #eee;
  padding: 0;
  margin: 0 auto;
  box-sizing: border-box;
  font-size: 14px;
  font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,
    Microsoft YaHei UI, Microsoft YaHei, 微软雅黑, Arial, sans-serif;
  position: relative;
  display: flex;
  flex-direction: column;
  background-size: 100% 100%;
}
.application-header {
  position: fixed;
  z-index: 99;
  height: 68px;
}
.application-tool {
  position: fixed;
  z-index: 100;
  width: 40px;
}
.application-content {
  position: absolute;
  width: 100%;
  bottom: 60px;
  top: 68px;
}
.application-footer {
  position: absolute;
  height: 60px;
  width: 100%;
  bottom: 0px;
}
.application-header.right {
  top: 0px;
  right: 40px;
  left: 0px;
}
.application-tool.right {
  top: 0px;
  right: 0px;
  bottom: 0px;
}
.application-content.right,
.application-footer.right {
  right: 40px;
  left: 0px;
  padding-right: 40px;
  box-sizing: border-box;
}
.application-header.left {
  top: 0px;
  right: 0px;
  left: 40px;
}
.application-tool.left {
  top: 0px;
  left: 0px;
  bottom: 0px;
}
.application-content.left,
.application-footer.left {
  top: 68px;
  left: 40px;
  right: 0px;
}
.application-header.top {
  top: 40px;
  right: 0px;
  left: 0px;
}
.application-tool.top {
  top: 0px;
  height: 40px;
  right: 0px;
  left: 0px;
  width: 100%;
}
.application-content.top,
.application-footer.top {
  top: 108px;
}
.custom-iframe {
  width: 100%;
  height: 0px;
  overflow: hidden;
}
@media screen and (max-width: 1024px) {
  .application-body {
    width: 1024px;
  }
}
</style>
